package B刷题.二分;

/**
 * @author wei.zhao
 * @description: 34.在排序数组中查找元素的第一个和最后一个位置
 * @date 2022年04月01日 15:42
 */
public class Code03_SearchRange {

    public static void main(String[] args) {
        Code03_SearchRange searchRange = new Code03_SearchRange();
        int[] range = searchRange.searchRange(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 9, 10, 11}, 8);
        System.out.println(range[0] + " " + range[1]);
    }

    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[]{-1, -1};
        if (nums == null || nums.length == 0) {
            return result;
        }
        int left = searchLeft(nums, target);
        int right = searchRight(nums, target);
        result[0] = left;
        result[1] = right;
        return result;
    }

    private int searchLeft(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                if (mid == 0 || nums[mid - 1] != target) {
                    return mid;
                } else {
                    right = mid - 1;
                }
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    private int searchRight(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right + 1) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                if (mid == nums.length - 1 || nums[mid + 1] != target) {
                    return mid;
                } else {
                    left = mid + 1;
                }
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

}
